<?php
// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org 
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------
namespace app\model\api;

use laytp\BaseModel;
use think\model\concern\SoftDelete;

class SkyGoods extends BaseModel
{
    protected $name = 'sky_goods';

    /**
     * 图鉴列表
     * @param $category
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function list($category){
        $guide_category = [];
        $guide = (new SkyGuide())->where('is_show','=',1)->cache(true)
            ->select()->toArray();
        foreach($guide as $item){
            $guide_category[$item['model']][] = $item['guide_name'];
        }
        $where = [];
        $where[] = ['status','=',1];
        if(!empty($category)){
            if(in_array($category,$guide_category[0])){
                $where[] = ['category','=',$category];
            }
            if(in_array($category,$guide_category[1])){
                if($category == '常驻物品'){
                    $where[] = ['category1','=',$category];
                }else{
                    $where[] = ['category2','=',$category];
                }

            }
        }

        $list = $this->field('name,remark,target as ancestor_id,tag,img_url as icon,category,sub_category,category2,relation_img')
            ->where($where)->cache(true)->select()->toArray();
        array_walk($list, function (&$item, $key){
            $item['relation_img']  = json_decode($item['relation_img'],true);
        });

        $return = [];
        foreach($list as $item){
            if($category == '常驻物品'){
                $return[$item['category2']]['name'] = $item['category2'];
                $return[$item['category2']]['list'][] = $item;
            }else{
                $return[$item['sub_category']]['name'] = $item['sub_category'];
                $return[$item['sub_category']]['list'][] = $item;
            }
        }

        return array_values($return);
    }

    /**
     * 根据id获取图鉴信息
     * @return array
     */
    public function info(){
        $list = $this
            ->cache(true)->column('remark,name,img_url as icon,target as ancestor_id,relation_img','id');
        array_walk($list, function (&$item, $key){
            $item['relation_img']  = json_decode($item['relation_img'],true);
        });

        return $list;
    }
}